package com.fizzkai.p2p.website.controller;

import com.fizzkai.p2p.core.domain.RealAuth;
import com.fizzkai.p2p.core.domain.UserInfo;
import com.fizzkai.p2p.core.service.IRealAuthService;
import com.fizzkai.p2p.core.service.IUserInfoService;
import com.fizzkai.p2p.core.util.AjaxResult;
import com.fizzkai.p2p.core.util.UserContext;
import com.fizzkai.p2p.website.util.RequireLogin;
import com.fizzkai.p2p.website.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class RealAuthController {

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IRealAuthService authService;

    @Value("${upload.files}")
    private String uploadPath;


    @RequestMapping("/realAuth")
    @RequireLogin
    public String realAuth(Model model){
        UserInfo current = userInfoService.getCurrent();
        // 判断 当前用户是否有 认证实名 权限
        if (current.isHasRealAuth()) {
            // 已经实名认证
            RealAuth realAuth = authService.get(current.getRealAuthId());
            model.addAttribute("auditing", false);
            model.addAttribute("realAuth", realAuth);
            return "realAuth_result";
        }
        // 没有 实名认证
        // 没有 real Auth Id 可以 提交 审核
        if (current.getRealAuthId() == null) {
            return "realAuth";
        }
        // 有 real Auth Id ，等待审核
        model.addAttribute("auditing", true);
        return "realAuth_result";
    }
    // 保存 认证资料
    @RequestMapping("/realAuth_save")
    @ResponseBody
    @RequireLogin
    public Object realAuth_save(RealAuth realAuth){
        authService.apply(realAuth);
        return new AjaxResult("提交成功");
    }

    // 文件上传
    @RequestMapping("/uploadImg")
    @ResponseBody
    public Object uploadImg(MultipartFile pic){
        String userPath = UserContext.getCurrentLoginInfo().getUsername();
        String string = UploadUtil.upload(pic, uploadPath + "/" +  userPath);
        return userPath + "/" + string;
    }
}
